// 数据库增删改查

//获取数据库对应模块
const MongoClient = require('mongodb').MongoClient;
// 数据库地址
const url = 'mongodb://localhost:27017';
//封装数据连接操作

function connect_db(callback){
    MongoClient.connect(url,{ useNewUrlParser: true },(err,db) =>{
        if(err) throw err;
        console.log("数据库已经连接");
        callback(db);
    });
}


// 插入数据
module.exports.insert = (dbname,col,obj,callback) => {
    connect_db((db) => {
        obj = (obj instanceof Array) ? obj : [obj];
        db.db(dbname).collection(col).insertMany(obj,(err,result) =>{
            if(err){
                callback(false);
                throw err;
            };
            console.log("插入的文档数量为: " + result.insertedCount);
            db.close();
            console.log(result.ops[0]);
            callback(result.ops[0]);
        });
    });
}

//查询数据
module.exports.find = (dbname,col,callback,...args) => {
    connect_db((db) => {
        // let {obj,mysort,m,n} = {
        //     obj:{},
        //     mysort:{},
        //     m:0,
        //     n:0
        // };
        let obj = {};
        let mysort = {};
        let m = 0;
        let n = 0;
        if(args.length == 1){
            obj = args[0];
        }else if(args.length == 2){
            obj = args[0];
            mysort = args[1];
        }else if(args.length == 3){
            obj = args[0];
            mysort = args[1];
            m = args[2];
        }else if(args.length == 4){
            obj = args[0];
            mysort = args[1];
            m = args[2];
            n = args[3];
        }
        db.db(dbname).collection(col).find(obj).sort(mysort).skip(m).limit(n).toArray((err,result) => {
            if(err) throw err;
            if(result.length == 0){
                console.log('查询已完成，未找到数据');
            }else{
                console.log('成功查到数据');
            }
            db.close();
            callback(result);
        });
    });
}

//更新数据
module.exports.update = (dbname,col,whereStr,target,callback) => {
    target = { $set:target };
    connect_db((db) => {
        db.db(dbname).collection(col).updateOne(whereStr,target,(err,result) =>{
            if(err) throw err;
            console.log(result+'更新数据成功');
            callback(true);
            db.close();
        });
    });
}

//删除数据
module.exports.delete = (dbname,col,whereStr,callback) => {
    connect_db((db) => {
        db.db(dbname).collection(col).deleteOne(whereStr,(err,result) => {
            if (err) throw err;
            console.log('已经删除数据'+result);
            callback(true);
            db.close();
        });
    });
}
